/**
 * @author 14544
 * @date 2020/4/16 15:39
 */
window.onload = function () {

    const myFileEle = document.querySelector('.myFile');
    const cancelEle = document.querySelector('.cancelUpload');
    const submitEle = document.querySelector('.submit');
    let uploader = null;
    let files = null;

    // 计算所选文件的总大小,并格式化文件单位
    let calculateTotalSize = ()=>{
        let totalBytes = 0;
        for (let i = 0; i < files.length; i++) { // 计算文件大小总和
            totalBytes+= files[i].size;
        }
        const sizeUnitArr = ["KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; // 展示单位
        let formatSize = '';
        for (let approxSize = totalBytes/1024,i=0; approxSize>1 ;approxSize/=1024,i++) {
            // 初始化时总和除以1024，approxSize表示kb，再除以1024就表示mb，以此类推，所以可以根据索引表示当前除了多少次1024，根据索引就获取对应的展示单位了
            approxSize = approxSize.toFixed(3);
            formatSize =  `${approxSize} ${sizeUnitArr[i]} format size in ${totalBytes} Bytes`;
            console.log(formatSize)
        }
    }

    myFileEle.addEventListener('change', function () {
        files = this.files;
        console.log(files)
        calculateTotalSize()
        if(myFileEle && myFileEle.style.display==='none') {
            uploadFun()
        }
    }, false)


    cancelEle.addEventListener('click', function () {
        uploader && uploader.abort()
    })


    submitEle.addEventListener('click', function () {
        if(myFileEle && myFileEle.style.display==='none') {
            myFileEle.click()  // 手动调用click方法来选择文件
        } else {
            uploadFun()
        }
    })

    // 上传函数
    function uploadFun() {
        uploader = new XMLHttpRequest();
        uploader.open('POST', '/gov/openapi/uploadFile', true);
        uploader.upload.onloadstart = function () {
            console.log('上传开始')
        }
        uploader.upload.onprogress = function () {
            console.log('上传中...')
        }
        uploader.upload.onload = function () {
            console.log('上传成功')
        }
        uploader.upload.onerror = function () {
            console.log('上传失败')
        }
        let formData = new FormData()
        formData.append('file', files[0])
        uploader.send(formData)
    }
}
